package three;


/**
 * 数组
 *
 * @author yangchuan
 * @version 1.0 create at 2021/3/17
 */
public class Array<E> {

    private E[] data;

    private int size;

    public Array(int capacity) {
        data = (E[]) new Object[capacity];
        size = 0;
    }

    public E getFirst() {
        return get(0);
    }

    //是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    //在末尾添加新元素
    public void addLast(E e) {
        add(size, e);
    }

    //在index的位置插入一个新元素
    public void add(int index, E e) {

        if (size == data.length) {
            resize(2 * data.length);
        }

        for (int i = size - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }

        data[index] = e;
        size++;

    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newData[i] = data[i];
        }
        data = newData;
    }

    public E get(int index) {
        return data[index];
    }

    public E remove(int index) {

        E ret = data[index];

        for (int i = index + 1; i < size; i++) {
            data[i - 1] = data[i];
        }
        size--;
        data[size] = null;

        if (size == data.length / 4 && data.length / 2 != 0) {
            resize(data.length / 2);
        }
        return ret;
    }

    public E removeFirst() {
        return remove(0);
    }

}
